package com.hm.service.config.microservice;


import com.hm.service.api.timer.TimerService;
import com.hm.service.api.user.UserService;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;


@Configuration
public class ServerConfig {

    private static final Logger logger = LoggerFactory.getLogger(ServerConfig.class);

    @Bean(name = {"ServerConfig"})
    public DubboBootstrap init() {
        logger.warn("=======>OkHttpClient初始化了<=======");

        DubboBootstrap bootstrap = DubboBootstrap.getInstance().application(getApplicationConfig());
        bootstrap.application(getApplicationConfig());
        bootstrap.registry(getRegistryConfig());
        bootstrap.reference(getReferenceConfig());
        bootstrap.reference(getTReferenceConfig());
        bootstrap.start();

        return bootstrap;
    }

    private static ReferenceConfig<UserService> getReferenceConfig() {
        ReferenceConfig<UserService> reference = new ReferenceConfig<>();
        reference.setInterface(UserService.class);
        reference.setVersion("1.0.1");//提供者设置了版本号就一定要加上
        return reference;
    }

    private static ReferenceConfig<TimerService> getTReferenceConfig() {
        ReferenceConfig<TimerService> reference = new ReferenceConfig<>();
        reference.setInterface(TimerService.class);
        reference.setVersion("1.0.1");//提供者设置了版本号就一定要加上
        return reference;
    }

    private static RegistryConfig getRegistryConfig() {
        RegistryConfig registryConfig = new RegistryConfig();
        registryConfig.setAddress("nacos://172.26.2.86:8848");
        registryConfig.setGroup("YDCG_SERVICE_GROUP");
        registryConfig.setUsername("nacos");
        registryConfig.setPassword("nacos");
        Map<String, String> parameters = new HashMap<>();
        parameters.put("namespace", "5cbb70a5-xxx-xxx-xxx-d43479ae0932");//消费者只能从同一个命名空间+分组中找到提供者
        parameters.put("register-consumer-url", "true");//注册接口级消费者
        registryConfig.setParameters(parameters);
        registryConfig.setTimeout(30 * 1000);//连接超时时间，默认 30s
        registryConfig.setSession(60 * 1000);//会话超时时间，默认 60s
        return registryConfig;
    }

    /**
     * 应用配置
     *
     * @return ApplicationConfig
     */
    private static ApplicationConfig getApplicationConfig() {
        ApplicationConfig applicationConfig = new ApplicationConfig();
        applicationConfig.setName("main-consumer");
        applicationConfig.setQosEnable(false);//关闭QOS
        //applicationConfig.setProtocol("2002");//
        return applicationConfig;
    }


}
